#!/bin/bash

# Flutter版本化构建脚本
# 用法: ./build_with_version.sh [平台] [构建类型]
# 平台: android, ios, windows, macos, linux, web
# 构建类型: debug, profile, release (默认: release)

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 获取参数
PLATFORM=${1:-android}
BUILD_TYPE=${2:-release}

# 获取当前日期和时间
DATE=$(date +"%Y%m%d")
TIME=$(date +"%H%M")
DATETIME="${DATE}_${TIME}"

# 从pubspec.yaml获取版本信息
VERSION=$(grep "^version:" pubspec.yaml | cut -d' ' -f2 | cut -d'+' -f1)
BUILD_NUMBER=$(grep "^version:" pubspec.yaml | cut -d' ' -f2 | cut -d'+' -f2)

# 获取真实的应用显示名称 (优先从Android获取，因为更常用)
if [ -f "android/app/src/main/AndroidManifest.xml" ]; then
    APP_NAME=$(grep "android:label=" android/app/src/main/AndroidManifest.xml | sed 's/.*android:label="\([^"]*\)".*/\1/' | head -1)
elif [ -f "ios/Runner/Info.plist" ]; then
    APP_NAME=$(grep -A1 "CFBundleDisplayName" ios/Runner/Info.plist | grep "<string>" | sed 's/.*<string>\(.*\)<\/string>.*/\1/' | head -1)
else
    # 如果找不到，则使用项目名称作为备用
    APP_NAME=$(grep "^name:" pubspec.yaml | cut -d' ' -f2)
fi

# 获取包名 (从android/app/build.gradle.kts)
if [ -f "android/app/build.gradle.kts" ]; then
    PACKAGE_NAME=$(grep "applicationId =" android/app/build.gradle.kts | cut -d'"' -f2 | head -1)
elif [ -f "android/app/build.gradle" ]; then
    PACKAGE_NAME=$(grep "applicationId" android/app/build.gradle | cut -d'"' -f2 | head -1)
else
    PACKAGE_NAME="未检测到"
fi

echo -e "${BLUE}📱 Flutter版本化构建工具${NC}"
echo -e "${YELLOW}应用名称:${NC} $APP_NAME"
echo -e "${YELLOW}版本号:${NC} $VERSION"
echo -e "${YELLOW}构建号:${NC} $BUILD_NUMBER"
echo -e "${YELLOW}包名:${NC} $PACKAGE_NAME"
echo -e "${YELLOW}平台:${NC} $PLATFORM"
echo -e "${YELLOW}构建类型:${NC} $BUILD_TYPE"
echo -e "${YELLOW}日期时间:${NC} $DATETIME"
echo ""

# 创建构建输出目录
BUILD_DIR="builds"
mkdir -p "$BUILD_DIR"

# 构建函数
build_android() {
    echo -e "${GREEN}🤖 开始构建Android APK...${NC}"
    
    if [ "$BUILD_TYPE" = "debug" ]; then
        flutter build apk --debug
        SOURCE_FILE="build/app/outputs/flutter-apk/app-debug.apk"
    elif [ "$BUILD_TYPE" = "profile" ]; then
        flutter build apk --profile
        SOURCE_FILE="build/app/outputs/flutter-apk/app-profile.apk"
    else
        flutter build apk --release
        SOURCE_FILE="build/app/outputs/flutter-apk/app-release.apk"
    fi
    
    # 生成新文件名 (使用包名的最后部分作为安全的文件名，包含构建号)
    SAFE_NAME=$(echo "$PACKAGE_NAME" | sed 's/.*\.//')
    NEW_NAME="${SAFE_NAME}_v${VERSION}+${BUILD_NUMBER}_${BUILD_TYPE}_${DATETIME}.apk"
    TARGET_FILE="$BUILD_DIR/$NEW_NAME"
    
    # 复制并重命名文件
    if [ -f "$SOURCE_FILE" ]; then
        cp "$SOURCE_FILE" "$TARGET_FILE"
        echo -e "${GREEN}✅ Android APK构建完成:${NC} $TARGET_FILE"
    else
        echo -e "${RED}❌ 构建失败: 找不到APK文件${NC}"
        exit 1
    fi
}

build_ios() {
    echo -e "${GREEN}🍎 开始构建iOS IPA...${NC}"
    
    if [ "$BUILD_TYPE" = "debug" ]; then
        flutter build ios --debug --no-codesign
    elif [ "$BUILD_TYPE" = "profile" ]; then
        flutter build ios --profile --no-codesign
    else
        flutter build ios --release --no-codesign
    fi
    
    # iOS需要额外步骤来生成IPA，这里只是示例
    SAFE_NAME=$(echo "$PACKAGE_NAME" | sed 's/.*\.//')
    echo -e "${YELLOW}⚠️  iOS构建完成，需要通过Xcode Archive生成IPA文件${NC}"
    echo -e "${YELLOW}建议的IPA文件名:${NC} ${SAFE_NAME}_v${VERSION}+${BUILD_NUMBER}_${BUILD_TYPE}_${DATETIME}.ipa"
}

build_windows() {
    echo -e "${GREEN}🪟 开始构建Windows应用...${NC}"
    
    if [ "$BUILD_TYPE" = "debug" ]; then
        flutter build windows --debug
    elif [ "$BUILD_TYPE" = "profile" ]; then
        flutter build windows --profile
    else
        flutter build windows --release
    fi
    
    # 压缩Windows构建结果
    SAFE_NAME=$(echo "$PACKAGE_NAME" | sed 's/.*\.//')
    NEW_NAME="${SAFE_NAME}_v${VERSION}+${BUILD_NUMBER}_windows_${BUILD_TYPE}_${DATETIME}.zip"
    TARGET_FILE="$BUILD_DIR/$NEW_NAME"
    
    if [ -d "build/windows/runner/Release" ]; then
        cd build/windows/runner/Release
        zip -r "../../../../$TARGET_FILE" .
        cd ../../../../
        echo -e "${GREEN}✅ Windows应用构建完成:${NC} $TARGET_FILE"
    else
        echo -e "${RED}❌ 构建失败: 找不到Windows构建文件${NC}"
        exit 1
    fi
}

build_macos() {
    echo -e "${GREEN}🍏 开始构建macOS应用...${NC}"
    
    if [ "$BUILD_TYPE" = "debug" ]; then
        flutter build macos --debug
    elif [ "$BUILD_TYPE" = "profile" ]; then
        flutter build macos --profile
    else
        flutter build macos --release
    fi
    
    # 压缩macOS构建结果
    SAFE_NAME=$(echo "$PACKAGE_NAME" | sed 's/.*\.//')
    NEW_NAME="${SAFE_NAME}_v${VERSION}+${BUILD_NUMBER}_macos_${BUILD_TYPE}_${DATETIME}.zip"
    TARGET_FILE="$BUILD_DIR/$NEW_NAME"
    
    # macOS的.app文件名通常使用项目名而不是显示名
    PROJECT_NAME=$(grep "^name:" pubspec.yaml | cut -d' ' -f2)
    if [ -d "build/macos/Build/Products/Release/${PROJECT_NAME}.app" ]; then
        cd "build/macos/Build/Products/Release"
        zip -r "../../../../../$TARGET_FILE" "${PROJECT_NAME}.app"
        cd ../../../../../
        echo -e "${GREEN}✅ macOS应用构建完成:${NC} $TARGET_FILE"
    else
        echo -e "${RED}❌ 构建失败: 找不到macOS构建文件${NC}"
        exit 1
    fi
}

build_linux() {
    echo -e "${GREEN}🐧 开始构建Linux应用...${NC}"
    
    if [ "$BUILD_TYPE" = "debug" ]; then
        flutter build linux --debug
    elif [ "$BUILD_TYPE" = "profile" ]; then
        flutter build linux --profile
    else
        flutter build linux --release
    fi
    
    # 压缩Linux构建结果
    SAFE_NAME=$(echo "$PACKAGE_NAME" | sed 's/.*\.//')
    NEW_NAME="${SAFE_NAME}_v${VERSION}+${BUILD_NUMBER}_linux_${BUILD_TYPE}_${DATETIME}.tar.gz"
    TARGET_FILE="$BUILD_DIR/$NEW_NAME"
    
    if [ -d "build/linux/x64/release/bundle" ]; then
        cd build/linux/x64/release
        tar -czf "../../../../$TARGET_FILE" bundle/
        cd ../../../../
        echo -e "${GREEN}✅ Linux应用构建完成:${NC} $TARGET_FILE"
    else
        echo -e "${RED}❌ 构建失败: 找不到Linux构建文件${NC}"
        exit 1
    fi
}

build_web() {
    echo -e "${GREEN}🌐 开始构建Web应用...${NC}"
    
    if [ "$BUILD_TYPE" = "debug" ]; then
        flutter build web --debug
    elif [ "$BUILD_TYPE" = "profile" ]; then
        flutter build web --profile
    else
        flutter build web --release
    fi
    
    # 压缩Web构建结果
    SAFE_NAME=$(echo "$PACKAGE_NAME" | sed 's/.*\.//')
    NEW_NAME="${SAFE_NAME}_v${VERSION}+${BUILD_NUMBER}_web_${BUILD_TYPE}_${DATETIME}.zip"
    TARGET_FILE="$BUILD_DIR/$NEW_NAME"
    
    if [ -d "build/web" ]; then
        cd build/web
        zip -r "../../$TARGET_FILE" .
        cd ../../
        echo -e "${GREEN}✅ Web应用构建完成:${NC} $TARGET_FILE"
    else
        echo -e "${RED}❌ 构建失败: 找不到Web构建文件${NC}"
        exit 1
    fi
}

# 根据平台执行对应的构建函数
case $PLATFORM in
    "android")
        build_android
        ;;
    "ios")
        build_ios
        ;;
    "windows")
        build_windows
        ;;
    "macos")
        build_macos
        ;;
    "linux")
        build_linux
        ;;
    "web")
        build_web
        ;;
    *)
        echo -e "${RED}❌ 不支持的平台: $PLATFORM${NC}"
        echo -e "${YELLOW}支持的平台: android, ios, windows, macos, linux, web${NC}"
        exit 1
        ;;
esac

echo ""
echo -e "${GREEN}🎉 构建完成！${NC}"
echo -e "${YELLOW}输出目录:${NC} $BUILD_DIR"
echo -e "${YELLOW}生成的文件命名格式:${NC} {应用名}_v{版本号}+{构建号}_{平台}_{构建类型}_{日期时间}.{扩展名}"